<template>
  <div class="verify-wrapper">
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script>
export default {
  props: {
    bgUrl: {
      type: String,
      default: ''
    },
    imgList: {
      type: Array,
      default: () => [{ url: '', x: 0, y: 0 }]
    },
    answer: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      canvas: null,
      ctx: null,
      markerText: 1,
      markerList: [],
      coords: []
    }
  },
  watch: {
    bgUrl () {
      this.init()
    }
  },
  mounted () {
    this.canvas = this.$refs.canvas
    this.ctx = this.canvas.getContext('2d')
    this.$nextTick(() => {
      this.init()
      this.canvas.addEventListener('click', this.onCanvasClick)
    })
  },
  methods: {
    save () {
      this.imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height)
    },
    restore () {
      this.ctx.putImageData(this.imageData, 0, 0)
    },
    onCanvasClick (e) {
      const { clientX, clientY } = e
      if (this.markerText > this.imgList.length) {
        this.markerText = 1
        this.restore()
      }
      this.drawMarker({
        x: clientX,
        y: clientY,
        text: this.markerText
      })

      if (this.markerText === this.imgList.length) {
        this.getVerifyResult()
      }
      this.markerText++
    },
    getVerifyResult () {
      const result = []
      for (let i = 0; i < this.markerList.length; i++) {
        const marker = this.markerList[i]
        const { x: mx, y: my, right: mr, bottom: mb } = marker
        const target = this._getMatchCoord(mx, my, mr, mb)
        result.push(target ? target.url : '')
      }
      console.log(result)
      this.markerList = []
    },
    _getMatchCoord (mx, my, mr, mb) {
      for (let j = 0; j < this.coords.length; j++) {
        const coord = this.coords[j]
        const { x: cx, y: cy, right: cr, bottom: cb } = coord
        if (mx >= cx && mx <= cr && my >= cy && my <= cb) {
          return coord
        } else if (mr >= cx && mr <= cr && my >= cy && my <= cb) {
          return coord
        } else if (my >= cy && my <= cb && mx >= cx && mx <= cr) {
          return coord
        } else if (mb >= cy && mb <= cb && mx >= cx && mx <= cr) {
          return coord
        }
      }
    },
    drawMarker ({ x, y, text }) {
      const { ctx } = this
      ctx.beginPath()
      ctx.fillStyle = 'green'
      ctx.arc(x, y, 15, 0, Math.PI * 2)
      ctx.fill()
      ctx.fillStyle = '#fff'
      ctx.font = '16px Arial'
      const { width: textW } = ctx.measureText(text)
      ctx.fillText(text, x - textW / 2, y + 12 / 2)
      ctx.closePath()
      this.markerList.push({
        // canvas没有提供获取高度的api，只能通过字体大小大概推算
        x, y, right: x + textW, bottom: y + 16, text
      })
    },
    init () {
      this.drawBg()
    },
    drawBg () {
      const { bgUrl, imgList, ctx, canvas } = this
      if (!bgUrl || !imgList) {
        return
      }

      const img = new Image()
      img.onload = (e) => {
        const { width, height } = img
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        canvas.width = width
        canvas.height = height
        ctx.drawImage(img, 0, 0, width, height)
        this.drawImgList()
      }
      img.src = bgUrl
    },
    drawImgList () {
      const { imgList, ctx } = this
      const coords = []
      for (let i = 0; i < imgList.length; i++) {
        const obj = imgList[i]
        const { url, x, y } = obj
        const img = new Image()
        coords.push({ url, x, y })
        img.onload = () => {
          const { width, height } = img
          coords[i].right = x + width
          coords[i].bottom = y + height
          ctx.drawImage(img, x, y)
          if (i + 1 === imgList.length) {
            this.coords = coords
            this.save()
          }
        }
        img.src = url
      }
    }
  }
}
</script>

<style>

</style>
